<!-- 预约确认 -->
<template>
	<view class="appointment-wrapper">
		<view class="header">
			<view class="left-icon">
				<image src="https://zhyl.setupgx.cn/attachment/app/icon/doctor.png"></image>
			</view>
			<view class="center-wrapper">
				<p>{{doctorInfo.DoctorName}}<span class="professional-label">{{doctorInfo.DoctorTitle}}</span></p>
				<p style="font-size: 0.6rem;">{{selectDeptName}}</p>
			</view>
		</view>
		<view class="content">
			<uni-section title="就诊信息" type="line">
				<uni-row>
					<!-- <uni-col :span="8">
						<view class="info-item-wrapper">
							<p>就诊医院</p>
							<p>澄迈县妇幼保健院</p>
						</view>
					</uni-col> -->
					<uni-col :span="8">
						<view class="info-item-wrapper">
							<p>医生</p>
							<p>{{doctorInfo.DoctorName}}</p>
						</view>
					</uni-col>
					<uni-col :span="8">
						<view class="info-item-wrapper">
							<p>就诊科室</p>
							<p>{{selectDeptName}}</p>
						</view>
					</uni-col>
					<uni-col :span="8">
						<view class="info-item-wrapper">
							<p>就诊人</p>
							<p>{{currentUserCard.names}}</p>
						</view>
					</uni-col>
					<uni-col :span="8">
						<view class="info-item-wrapper">
							<p>诊疗费</p>
							<p>￥{{timeFrame.Money}}元</p>
						</view>
					</uni-col>
					<uni-col :span="24">
						<view class="info-item-wrapper">
							<p>就诊时间</p>
							<p>{{timeFrame.regBegin}} {{timeFrame.Time}}</p>
						</view>
					</uni-col>
				</uni-row>
				<div class="clearfix"></div>
			</uni-section>
			
		</view>
		<div class="clearfix"></div>
		<div style="margin-top: 10px;"></div>
		
		<p style="line-height: 30px; margin: 0 10px 0px 10px;">为了方便您安全顺利就诊，请注意以下事项：</p>
		<p style="line-height: 30px; margin: 0 10px 0px 10px;">（1）预约成功患者请按时到指定科室进行候诊，具体排号顺序以现场排队叫号为主。</p>
		<p style="line-height: 30px; margin: 0 10px 0px 10px;">
			（2）需要退号且未就诊患者请在当日在小程序上自行退号退款，<span style="font-weight: bold; color: red;">超过</span>就诊时间<span style="font-weight: bold; color: red;">24小时</span>，<span style="font-weight: bold; color: red;">过期不予退号退款</span>。
			</p>
		
		<div style="margin-top: 10px;"></div>
		<button :disabled="addorderBtnDisabled" type="primary" @click="affirmModalVisible = true">预约</button>
		
		<yangr-msg v-if="yangrMsgShow" :title="yangrMsgTitle" type="error" :info="yangrMsgMessage" btn="确定"
			@yangrMsgEvent="closeYangrMsg"></yangr-msg>
			
		<u-modal :show="affirmModalVisible" @confirm="api_addorder" @cancel="affirmModalVisible = false" :title="'确认'"
			:asyncClose="true" :showCancelButton="true">
			<view class="slot-content">
				<rich-text :nodes="'确定要挂号吗？'"></rich-text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		randomString
	} from '../../common/StringUitl.js'
	import yangrMsg from "@/components/yangr-msg/yangr-msg.vue"
	import onlineRegistrationApi from './onlineRegistrationApi.js'
	import customLogApi from '../../common/customLogApi.js'
	export default {
		components: {
			yangrMsg
		},
		data() {
			return {
				selectDeptName: '',
				startdate: '',
				timeFrame: {},
				doctorInfo: {},
				payType: '14',
				currentUserCard: {},
				addorderBtnDisabled: false,
				
				affirmModalVisible: false,
				
				yangrMsgTitle: '',
				yangrMsgMessage: '',
				yangrMsgShow: false
			}
		},
		onLoad(option) {
			this.currentUserCard = uni.getStorageSync('current_user_card')
			let timeFrame = JSON.parse(option.timeFrame)
			let doctorInfo = JSON.parse(option.doctorInfo)
			this.selectDeptName = option.selectDeptName
			this.startdate = option.startdate
			this.timeFrame = timeFrame
			this.doctorInfo = doctorInfo
			console.log(this.timeFrame)
			console.log(this.doctorInfo)
			console.log(encodeURIComponent('/pages/tabbar/index/index'))
		},
		methods: {
			closeYangrMsg() {
				this.yangrMsgShow = false
			},
			api_addorder() {
				this.addorderBtnDisabled = true
				let userOpenid = uni.getStorageSync('openid')
				let currentUserCard = uni.getStorageSync('current_user_card')
				onlineRegistrationApi.api_guahao_addorder(userOpenid, {
						"cardid": currentUserCard.numcard,
						"deptid": this.doctorInfo.DepartmentId,
						"deptname": this.doctorInfo.DiagnosisRoomName,
						"roomid": this.doctorInfo.DiagnosisRoomId,
						"roomname": this.doctorInfo.DiagnosisRoomName,
						"docid": this.doctorInfo.DoctorId,
						"docname": this.doctorInfo.DoctorName,
						"date": this.startdate,
						"timezone": "0",
						"starttime": this.timeFrame.regBegin.replaceAll('/', '-'),
						"endtime": this.timeFrame.regEnd.replaceAll('/', '-'),
						"money": this.timeFrame.Money,
						"paytype": this.payType
					}).then((res) => {
						console.log(res)
						this.api_wxpay(res.id, res.ordersn, res.money)
					})
			},
			
			api_wxpay(id, ordersn, money) {
				let that = this
				let userOpenid = uni.getStorageSync('openid')
				onlineRegistrationApi.api_guahao_icbcpay(userOpenid, ordersn, money).then((res) => {
					console.log(res)
					let order_id = res.order_id
					let wx_data_package = JSON.parse(res.wx_data_package)
					let orderInfo = {
						"appid": wx_data_package.appid, // 应用ID（AppID）
						"partnerid": "1600769412", // 商户号（PartnerID）
						"prepayid": res.prepayId, // 预支付交易会话ID
						"package": wx_data_package.package, // 固定值
						"noncestr": wx_data_package.noncestr, // 随机字符串
						"timestamp": wx_data_package.timestamp, // 时间戳（单位：秒）
						"sign": wx_data_package.sign, // 签名，这里用的 MD5 签名
						"signtype": wx_data_package.signType
					}
					console.log(orderInfo)
					uni.requestPayment({
						"provider": "wxpay", //固定值为"wxpay"
						"timeStamp": orderInfo.timestamp,
						"nonceStr": orderInfo.noncestr,
						"package": orderInfo.package,
						"signType": orderInfo.signtype,
						"paySign": orderInfo.sign,
						success: (res) => {
							console.log(res)
							console.log("支付成功");
							that.api_paysucc(id, ordersn, order_id)
						},
						fail: (err) => {
							console.log('支付失败:' + JSON.stringify(err));
							customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "挂号流程：支付失败，返回结果：" + JSON.stringify(err))
							if (err.errMsg == 'requestPayment:fail cancel') {
								that.addorderBtnDisabled = false
								uni.showToast({
									icon: 'none',
									title: '您已取消支付'
								})
							} else {
								uni.showToast({
									icon: 'none',
									title: '支付失败'
								})
							}
						}
					});
					// onlineRegistrationApi.pay(orderInfo).then((res) => {
					// 	console.log(res)
					// 	// if (res.errMsg == 'requestPayment:ok') {
					// 		console.log("支付成功");
					// 		that.api_paysucc(id, ordersn, order_id)
					// 	// }
					// }).catch((err) => {
					// 	console.log('支付失败:' + JSON.stringify(err));
					// 	if (err.errMsg == 'requestPayment:fail cancel') {
					// 		that.addorderBtnDisabled = false
					// 		uni.showToast({
					// 			icon: 'none',
					// 			title: '您已取消支付'
					// 		})
					// 	} else {
					// 		uni.showToast({
					// 			icon: 'none',
					// 			title: '支付失败'
					// 		})
					// 	}
					// })
				})
			},
			api_paysucc(id, ordersn, order_id) {
				customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "挂号流程：paysucc接口开始调用")
				let userOpenid = uni.getStorageSync('openid')
				onlineRegistrationApi.api_guahao_paysucc(userOpenid, id, order_id).then((res) => {
					customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "挂号流程：paysucc接口调用成功，返回数据：" + JSON.stringify(res))
					if (res.succ == true || res.succ == 1) {
						this.api_jiuzhenreg(ordersn, res.paytime, res.orderid)
					}else {
						onlineRegistrationApi.api_guahao_paysucc(userOpenid, id, order_id).then((res) => {
							if (res.succ != true) {
								customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "挂号流程：支付状态更新失败，返回数据：" + JSON.stringify(res))
								uni.navigateTo({
									url: '/pages/global/errorMessage?msg=支付状态更新失败'
								})
							}
						})
					}
				})
			},
			api_jiuzhenreg(ordersn, paytime, orderid) {
				customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "挂号流程：reg接口开始调用")
				let currentUserCard = uni.getStorageSync('current_user_card')
				let userOpenid = uni.getStorageSync('openid')
				let form = {
					"CardID": currentUserCard.numcard,
					"DiagnosisRoomId": this.doctorInfo.DiagnosisRoomId,
					"DoctorId": this.doctorInfo.DoctorId,
					"ScheduleDate": this.startdate,
					"TimePeriod": this.timeFrame.TimeEnum,
					"RegistrationTypeId": this.timeFrame.RegistrationTypeId,
					"Money": this.timeFrame.Money,
					"HisPaymentMethodEnum": this.payType,
					"PayTime": paytime,
					"OutTradeNo": ordersn,
					"DepartmentId": this.doctorInfo.DepartmentId,
					"regStart": this.timeFrame.regBegin.replaceAll('/', '-'),
					"regEnd": this.timeFrame.regEnd.replaceAll('/', '-')
				}
				onlineRegistrationApi.api_reg(userOpenid, orderid, form).then((res) => {
					customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "挂号流程：reg接口调用成功，返回数据：" + JSON.stringify(res))
					console.log(res)
					if (res.status == 1 && res.data instanceof Object) {
						const params = {
							env: 'prod',
							hospitalId: '37868',
							redirectUrl: '/pagesB/onlineRegistration/index',
							sceneType: '1',
							healthCardId: currentUserCard.ecard_no,
							orderTotal: this.timeFrame.Money
						}
						uni.navigateTo({
							url: `plugin://healthCardPlugins/complete?env=${params.env}&hospitalId=${params.hospitalId}&sceneType=${params.sceneType}&redirect_url=${encodeURIComponent(params.redirectUrl)}&orderTotal=${params.orderTotal}&healthCardId=${params.healthCardId}`
						})
						// uni.redirectTo({
						// 	url: '/pages/global/successMessage?msg=挂号成功'
						// })
					} else {
						// uni.showToast({
						// 	title: res.data,
						// 	icon: 'none',
						// 	duration: 5000
						// })
						this.yangrMsgShow = true
						this.yangrMsgMessage = res.data
					}
					// this.$app._post_form2('entry/wxapp/apiregistration.checkin', {
					// 	"cardid": currentUserCard.numcard,
					// 	"regid": res.data.RegistId
					// }, (res) => {
					// 	console.log(res)
					// 	uni.redirectTo({
					// 		url: '/pages/global/successMessage?msg=挂号成功'
					// 	})
					// })
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.appointment-wrapper {
		width: 100%;
		height: 100%;
		position: relative;
		color: #757575;
		padding: 5px;
		box-sizing: border-box;

		.header {
			position: relative;
			display: flex;
			flex-direction: row;
			border-bottom: 1px solid #EEEEEE;
			background-image: linear-gradient(to right, #41C177, #c8e6c9);
			padding: 12px 15px;
			color: #ffffff;

			.left-icon {
				width: 50px;
				height: 50px;
				border-radius: 50px;
				background-color: #4caf50;
				display: flex;
				flex-direction: row;
				align-items: center;
				text-align: center;
				justify-content: center;

				image {
					width: 30px;
					height: 30px;
				}
			}

			.center-wrapper {
				display: flex;
				flex: 1;
				flex-direction: column;
				padding-left: 10px;
				font-size: 1rem;

				.professional-label {
					margin-left: 6px;
					margin-right: 6px;
					font-size: 0.8rem;
				}
			}
		}

		.content {
			margin-top: 5px;
			background-color: #ffffff;
			box-sizing: border-box;

			.info-item-wrapper {
				width: 100%;
				box-sizing: border-box;
				padding: 10px;
				text-align: center;

				p {
					font-size: .8rem;
				}

				p:first-child {
					font-size: .7rem;
					color: #bdbdbd;
				}

			}
		}
	}
</style>